import java.util.ArrayList;
import java.util.Map;

public class MutualFundRepository {

	private static MutualFundRepository repository;
	private static ArrayList<MutualFund> mutualFunds = new ArrayList<MutualFund>();

	private MutualFundRepository() {
	}

	public static MutualFundRepository getMutualFundRepository() {
		if (repository == null) {
			repository = new MutualFundRepository();
		}
		return repository;
	}

	public void addMutualFunds(MutualFund mutualFund) {
		mutualFunds.add(mutualFund);
	}

	public ArrayList<MutualFund> getMutualFund() {
		return mutualFunds;
	}

	public MutualFund getMutualFund(int mutualFundId) {
		for (int i = 0; i < mutualFunds.size(); i++) {
			MutualFund mutualFund = mutualFunds.get(i);
			if (mutualFund.getMutualFundId() == mutualFundId) {
				return mutualFunds.get(i);
			}
		}
		return null;
	}

	public double getMutualFundPrice(int mutualFundId) {
		MutualFund mutualFund = getMutualFund(mutualFundId);
		return mutualFund.getMutualFundPrice();
	}

	public void calculateLatestMfPrice() {
		for (MutualFund mutualFund : mutualFunds) {
			double totalStockPrice = 0;
			double totalQuantity = 0;
			for (Map.Entry<Stock, Integer> stockDetail : MutualFund
					.getStockDetails().entrySet()) {
				Stock oldStock = stockDetail.getKey();
				int stockId = oldStock.getStockId();
				double quantity = stockDetail.getValue();
				Stock stock = StockRepository.getStockRepository().getStock(
						stockId);
				if (stock != null) {
					totalStockPrice += (stock.getStockPrice() * ((double) quantity));
					totalQuantity += quantity;
					MutualFund.getStockDetails().remove(oldStock);
					MutualFund.getStockDetails().put(stock, (int) quantity);
				}
			}
			double mutualFundPrice = totalStockPrice / totalQuantity;
			mutualFund.setMutualFundPrice(mutualFundPrice);
		}
	}

	public ArrayList<MutualFund> getAllMutualFunds(int portfolioId) {
		ArrayList<MutualFund> allMutualFunds = new ArrayList<MutualFund>();
		for (int i = 0; i < mutualFunds.size(); i++) {
			MutualFund mutualFund = mutualFunds.get(i);
			if (mutualFund.getPortfolioId() == portfolioId) {
				allMutualFunds.add(mutualFund);
			}
		}
		return allMutualFunds;
	}
}
